﻿/***************************************************************
 * 开发人员：网魂小兵@http://www.mozlite.com
 * 
 * 目标标本：4.0.30319.239
 * 
 * 最后修改：2011/11/10 15:34:31
 * ************************************************************/
namespace Mozlite.Common
{
    using System;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Collections.Generic;
    using Mozlite.Common.Configuration;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 用户Cookie类。
    /// </summary>
    public class UserCookie
    {
        private HttpContext context;
        private string cookieKey;
        private string cookieName;
        private User user;
        /// <summary>
        /// 用户Cookie实例对象。
        /// </summary>
        protected HttpCookie userCookie;
        private static Regex regex = new Regex(@"[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>
        /// 初始化<see cref="T:Mozlite.Common.UserCookie"/>。
        /// </summary>
        /// <param name="user">用户实例对象。</param>
        public UserCookie(User user)
        {
            this.user = user;
            this.cookieName = "Mozlite.Common-UserCookie" + user.UserID.ToString();
            this.context = AppContext.Current.Context;
            if ((this.context != null) && (this.context.Request != null))
            {
                this.userCookie = this.context.Request.Cookies[this.cookieName];
                this.cookieKey = string.Format("hfg-{0}", SiteSettings.Current.SettingsID);
            }
            if (this.userCookie == null)
            {
                this.userCookie = new HttpCookie(this.cookieName);
            }
            else
            {
                this.userCookie = this.context.Request.Cookies[this.cookieName];
            }
        }
        /// <summary>
        /// 移除用户Cookie。
        /// </summary>
        /// <param name="cookie">Cookie实例。</param>
        public void DeleteCookie(HttpCookie cookie = null)
        {
            if (cookie == null)
                cookie = this.userCookie;
            if (cookie == null)
                return;
            string input = SiteSettings.Default.CookieDomain;
            string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;
            if (!string.IsNullOrEmpty(input) && regex.IsMatch(input) && (absoluteUri.IndexOf(input) > -1))
            {
                cookie.Path = "/";
                cookie.Domain = input;
            }
            cookie.Expires = new DateTime(0x7cf, 10, 12);
            this.context.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 更新用户最后访问Cookie。
        /// </summary>
        public void UpdateLastVisit()
        {
            if (this.userCookie["mra"] == null)
            {
                this.userCookie["lv"] = DateTime.Parse("1/1/1999").ToString("r");
            }
            else
            {
                this.userCookie["lv"] = this.userCookie["mra"];
            }
            this.WriteCookie();
        }
        /// <summary>
        /// 更新最后激活时间。
        /// </summary>
        public void UpdateMostRecentActivity()
        {
            this.userCookie["mra"] = DateTime.Now.ToString("r");
            this.WriteCookie();
        }
        /// <summary>
        /// 写入用户Cookie实例。
        /// </summary>
        protected void WriteCookie()
        {
            this.WriteCookie(this.userCookie, 0x16d, true);
        }
        /// <summary>
        /// 写入用户Cookie实例。
        /// </summary>
        /// <param name="cookie">用户Cookie实例对象。</param>
        /// <param name="days">到期时间（日）。</param>
        /// <param name="autoLogin">是否自动登录。</param>
        public void WriteCookie(HttpCookie cookie, int days, bool autoLogin)
        {
            string input = SiteSettings.Default.CookieDomain;
            string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;
            if (!string.IsNullOrEmpty(input) && regex.IsMatch(input) && (absoluteUri.IndexOf(input) > -1))
            {
                cookie.Path = "/";
                cookie.Domain = input;
            }
            if (autoLogin)
            {
                cookie.Expires = DateTime.Now.AddDays((double)days);
            }
            this.context.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 获取用户最后访问时间。
        /// </summary>
        public DateTime LastVisit
        {
            get
            {
                if (this.userCookie["lv"] == null)
                {
                    this.UpdateLastVisit();
                }
                return DateTime.Parse(this.userCookie["lv"]);
            }
        }
        /// <summary>
        /// 获取Cookie值。
        /// </summary>
        /// <returns>返回Cookie字符串。</returns>
        public string GetValue()
        {
            if (userCookie == null)
                return null;
            return userCookie.Value;
        }
    }
}